package com.sz.controller;

import com.sz.constant.MessageConstant;
import com.sz.entity.Result;
import com.sz.exception.MyException;
import com.sz.pojo.OrderSetting;
import com.sz.service.OrderSettingService;
import com.sz.utils.POIUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/ordersetting")
public class OrderSettingController {

    @Autowired
    private OrderSettingService orderSettingService;

    @PostMapping("/upload")
    public Result upload(MultipartFile excelFile) {
        try {
            //调用POIUtils读取Excel内容
            //每一行就是一个字符串数组，每个数组就代表着一个预约设置对象
            //[0]日期  [1]最大预约数
            List<String[]> list = POIUtils.readExcel(excelFile);
            //转成List<orderSetting>实体类
            List<OrderSetting> orderSettingList =new ArrayList<OrderSetting>(list.size());
            //日期格式解析
            SimpleDateFormat sdf = new SimpleDateFormat(POIUtils.DATE_FORMAT);
            for (String[] arr : list) {
                //日期
                String orderDateStr =arr[0];
                //最大预约数
                String numberStr =arr[1];
                //构建预约设置实体
                OrderSetting os = new OrderSetting(sdf.parse(orderDateStr), Integer.valueOf(numberStr));
                //添加到list集合中
                orderSettingList.add(os);
            }
            //调用业务
            orderSettingService.doImport(orderSettingList);
            //返回结果给页面
            return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false,e.getMessage());
        } catch (ParseException e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }

    }

}
